package com.example.medispider.service.detail;

import com.example.medispider.pojo.detail.detail.DeatilApiResponse;
import com.example.medispider.pojo.detail.detail.DetailPageBean;
import com.example.medispider.pojo.detail.detail.SettlementDetail;
import com.example.medispider.pojo.detail.userinfo.BriefUserInfo;
import com.example.medispider.pojo.detail.userinfo.UserInfo;
import com.example.medispider.pojo.detail.userinfo.UserInfoResponse;
import com.example.medispider.utils.PageRequestBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.utils.HttpConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DetailPageProcessor implements PageProcessor {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final Site site;
    private final String userInfoUrl = "https://portal.hub.hsip.gov.cn/mbs-dy-420500/web/multisearch/settleAccount/querySetlDDTOList";
    private final String detailUrl = "https://portal.hub.hsip.gov.cn/mbs-dy-420500/web/feeList/operations/queryFeeList";
    private int pageSize = 100;

    @Autowired
    public DetailPageProcessor(Site site) {
        this.site = site;
    }

    @Override
    public void process(Page page) {
        try {
            String url = page.getUrl().get();
            if (userInfoUrl.equals(url)) {
                String userInfoApiResponse = page.getRawText();
                UserInfoResponse userInfoResponse = objectMapper.readValue(userInfoApiResponse, UserInfoResponse.class);
                if (userInfoResponse.isSuccess()) {
                    List<UserInfo> data = userInfoResponse.getData().getPageBean().getData();
                    if (!data.isEmpty()) {
                        UserInfo userInfo = data.getFirst();
                        HttpRequestBody requestBody = userInfo.toQueryString(pageSize);
                        Request request = new Request(detailUrl);
                        request.setMethod(HttpConstant.Method.POST); // 设置请求方法为 POST
                        request.setRequestBody(requestBody);
                        page.addTargetRequest(request);
                        page.setSkip(true); // 跳过这个页面的处理
                    } else {
                        String body = new String(page.getRequest().getRequestBody().getBody());
                        Map<String, Object> params = PageRequestBuilder.parseFormParams(body);
                        BriefUserInfo briefUserInfo = new BriefUserInfo();
                        briefUserInfo.setPsnNo(params.get("psnNo").toString());
                        briefUserInfo.setSetlId(params.get("setlId").toString());
                        System.err.println("该结算ID未查到明细：" + body);
                        page.putField("emptyDetail", briefUserInfo);
                    }
                } else {
                    // 处理错误情况
                    System.err.println("患者身份信息请求失败: " + userInfoResponse.getMessage());
                    page.setSkip(true); // 跳过这个页面的处理
                }
            } else if (detailUrl.equals(url)) {
                String detailApiResponseJson = page.getRawText();
                DeatilApiResponse detailApiResponse = objectMapper.readValue(detailApiResponseJson, DeatilApiResponse.class);
                if (detailApiResponse.isSuccess()) {
                    DetailPageBean pageBean = detailApiResponse.getData().getPageBean();
                    List<SettlementDetail> details = pageBean.getData();
                    if (details != null && !details.isEmpty()) {
                        // 将数据放入page，供Pipeline处理
                        page.putField("details", details);
                        // 首次请求，添加后续分页请求
                        if (pageBean.isFirstPage()) {
                            int pages = pageBean.getPages();
                            if (pages > 1) {
                                Request currentRequest = page.getRequest();
                                ArrayList<Request> pageRequests = PageRequestBuilder.createPageRequests(currentRequest, pages);
                                for (Request pageRequest : pageRequests) {
                                    page.addTargetRequest(pageRequest);
                                }
                            }
                        }
                    } else {
                        String body = new String(page.getRequest().getRequestBody().getBody());
                        System.err.println("明细分页查找为空：" + body);
                        page.setSkip(true); // 跳过这个页面的处理
                    }
                } else {
                    // 处理错误情况
                    System.err.println("明细API请求失败: " + detailApiResponse.getMessage());
                    page.setSkip(true); // 跳过这个页面的处理
                }
            } else {
                System.err.println("未知url: " + url);
                page.setSkip(true); // 跳过这个页面的处理
            }
        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
            page.setSkip(true);
        }
    }


    @Override
    public Site getSite() {
        return site;
    }

    public DetailPageProcessor setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }
}
